package com.lagou.controller;

import com.lagou.feign.EmailServiceFeignClient;
import com.lagou.po.CodePO;
import com.lagou.service.CodeService;
import com.lagou.utils.CodeGenerateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @AUTHOR: yb.feng
 * @DATE: 2020/7/1 20:33
 * @DESC:
 */
@RestController
@RequestMapping("/api")
public class CodeController {

    @Autowired
    private CodeService codeService;

    @Autowired
    private EmailServiceFeignClient emailServiceFeignClient;

    @RequestMapping("/code/create/{email}")
    public boolean generateCode(@PathVariable String email){
        String code = CodeGenerateUtil.get();
        CodePO codePO = new CodePO();
        codePO.setCode(code);
        codePO.setEmail(email);
        codePO.setCreatetime(new Date());
        codePO.setExpiretime(CodeGenerateUtil.getExpireTime());
        codeService.saveCode(codePO);
        emailServiceFeignClient.sendEmail(email, code);
        return true;
    }

    @RequestMapping("/code/validate/{email}/{code}")
    public Integer validateCode(@PathVariable String email, @PathVariable String code){
        CodePO realCode = codeService.getCode(email);
        if (realCode.getExpiretime().getTime() < System.currentTimeMillis()){
            return 2;
        }
        if (!code.equals(realCode.getCode())){
            return 1;
        }
        return 0;
    }
}
